package com.yhd.rabbit.work;

import com.rabbitmq.client.*;
import com.yhd.rabbit.util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 二十
 * @since 2022/1/14 2:24 下午
 */
public class ConsumerB {
    private static final String QUEUE_NAME= "work_yhd";

    public static void main(String[] args)throws Exception {
        //获取连接
        Connection conn = ConnectionUtil.getConnection();
        //开启通道
        Channel channel = conn.createChannel();
        //声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //设置每次只处理一条消息
        channel.basicQos(1);
        //构建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body);
                System.out.println(message);
                channel.basicAck(envelope.getDeliveryTag(),false);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        //监听队列
        channel.basicConsume(QUEUE_NAME,false,consumer);
    }
}
